package com.fruit.controller.wap.lightpay;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttribute;
import org.springframework.web.servlet.ModelAndView;

import com.fruit.alipay.util.AlipayUtil;
import com.fruit.common.CookieUtil;
import com.fruit.common.WebCommonUtil;
import com.fruit.constants.LightPayConstant;
import com.fruit.controller.base.BaseController;
import com.fruit.pojo.lightpay.LightPayCashier;
import com.fruit.resolver.DefiniteException;
import com.fruit.service.lightpay.LightPayManager;
import com.fruit.util.CommonUtil;
import com.fruit.util.ResultInfo;
import com.fruit.util.ResultUtil;

import lombok.extern.slf4j.Slf4j;

/**
 * 收银台Controller <br/>
 * @author shibeilei
 * @version 2017.11.30 12:20
 */
@Slf4j
@Controller
@RequestMapping(value = "/wap/lightpay/")
public class LightPayController extends BaseController {

	@Autowired
	private LightPayManager lightPayService;

	/**
	 * 我的收银台 <br/>
	 * @param lpc 支付信息
	 * @return 支付页
	 * @author shibeilei
	 * @version 2017.11.30 11:40
	 */
	@RequestMapping(value = "lightPayCashier", method = { RequestMethod.POST, RequestMethod.GET })
	public ModelAndView lightPayCashier(LightPayCashier lpc, @SessionAttribute("userId") Integer userId) {
		String tradeId = CommonUtil.getUUID();
		lpc.setUserId(userId);
		log.info("[{}]-【我的收银台】-【用户：{}】-【开始】", tradeId, lpc.getUserId());
		ModelAndView view = this.getModelAndView();

		log.info("[{}]-【我的收银台】-【调用查看交易流水服务】", tradeId);
		Map<String, Object> resMap = lightPayService.getTransactionFlow(tradeId, lpc.getTransactionCode());
		ResultInfo ri = (ResultInfo) resMap.get("result");
		if (ResultInfo.ERROR.equals(ri.getState())) {
			log.error("[{}]-【我的收银台】-【异常】-【{}：{}】", tradeId, ri.getCode(), ri.getMessage());
			throw new DefiniteException(ri.getMessage());
		}

		view.addObject("resMap", resMap);
		view.setViewName("lightpay/myCashier");
		log.info("[{}]-【我的收银台】-【结束】", tradeId);
		return view;
	}

	/**
	 * 支付宝WAP支付 <br/>
	 * @param lpc 支付信息
	 * @param session session
	 * @return 返回信息
	 * @author shibeilei
	 * @version 2017.11.30 11:40
	 */
	@RequestMapping(value = "/confirm_alipay_pay", method = { RequestMethod.POST, RequestMethod.GET })
	@ResponseBody
	@SuppressWarnings("unchecked")
	public Map<String, Object> alipayWapPay(@RequestBody LightPayCashier lpc, HttpSession session) {
		String tradeId = CommonUtil.getUUID();
		Map<String, Object> resMap = new HashMap<String, Object>();
		try {
			Integer userId = (Integer) session.getAttribute("userId");
			lpc.setUserId(userId);
			log.info("[{}]-【支付宝支付】-【交易流水号：{}】-【用户：{}】-【开始】", tradeId, lpc.getTransactionCode(), userId);
			log.info("[{}]-【支付宝支付】-【调用支付宝服务】", tradeId);
			if (!LightPayConstant.ChannelType.isExists(lpc.getChannelType())) {
				resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "error", "支付渠道不存在"));
				return resMap;
			}
			resMap = lightPayService.saveAlipayPayCashier(tradeId, lpc);
			ResultInfo ri = (ResultInfo) resMap.get("result");
			if (ResultInfo.SUCCESS.equals(ri.getState())) {
				Map<String, String> params = (Map<String, String>) resMap.get("returnParams");
				String url = AlipayUtil.alipayWap(params);
				if (StringUtils.isNotEmpty(url)) {
					log.error("[{}]-【支付宝支付】-【成功】", tradeId);
					resMap.put("result", this.initResult(ResultInfo.SUCCESS, "OK", null));
					resMap.put("url", url);
				} else {
					log.error("[{}]-【支付宝支付】-【异常】-【{}：{}】", tradeId, ri.getCode(), ri.getMessage());
					resMap.put("result", this.initResult(ResultInfo.ERROR, "fail", "系统繁忙", null));
				}
			} else {
				log.error("[{}]-【支付宝支付】-【异常】-【{}：{}】", tradeId, ri.getCode(), ri.getMessage());
			}

		} catch (Exception e) {
			e.printStackTrace();
			resMap.put("result", this.initResult(ResultInfo.ERROR, "exception", "系统繁忙", null));
			log.error("[{}]-【支付宝支付】-【异常】-【{}：{}】", tradeId, "exception", "系统繁忙");
		}
		log.info("[{}]-【支付宝支付】-【结束】", tradeId);
		return resMap;

	}

	/**
	 * APP微信支付 <br/>
	 * @param lpc 支付信息
	 * @param session session
	 * @param request request
	 * @return 返回信息
	 * @author shibeilei
	 * @version 2017.11.30 11:40
	 */
	@RequestMapping(value = "weChatPay", method = { RequestMethod.POST, RequestMethod.GET })
	@ResponseBody
	public Map<String, Object> wechatPay(@RequestBody LightPayCashier lpc, HttpSession session, HttpServletRequest request) {
		this.logBefore(logger, "APP微信支付");
		String tradeId = CommonUtil.getUUID();
		Map<String, Object> resMap = new HashMap<String, Object>();
		try {
			Integer userId = (Integer) session.getAttribute("userId");
			log.info("[{}]-【微信支付】-【交易流水号：{}】-【用户：{}】-【开始】", tradeId, lpc.getTransactionCode(), userId);
			log.info("[{}]-【微信支付】-【调用微信服务】", tradeId);
			if (!LightPayConstant.ChannelType.isExists(lpc.getChannelType())) {
				resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "error", "支付渠道不存在"));
				return resMap;
			}
			
			if(LightPayConstant.ChannelType.WAP.equals(lpc.getChannelType())){
				String openId = CookieUtil.getValue(request, "publicOpenid");
				if(StringUtils.isEmpty(openId)){
					resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "openId_error", "openId不存在"));
					return resMap;
				}
				
				lpc.setOpenid(openId);
			}
			
			lpc.setUserId(userId);
			lpc.setIp(WebCommonUtil.getIpAddr(request));
			resMap = lightPayService.saveWechatPayCashier(tradeId, lpc);
			ResultInfo ri = (ResultInfo) resMap.get("result");
			if (ResultInfo.ERROR.equals(ri.getState())) {
				log.error("[{}]-【微信支付】-【异常】-【{}：{}】", tradeId, ri.getCode(), ri.getMessage());
			} else {
				log.info("[{}]-【微信支付】-【成功】", tradeId);
			}
		} catch (Exception e) {
			e.printStackTrace();
			resMap.put("result", this.initResult(ResultInfo.ERROR, "exception", "系统繁忙", null));
			log.error("[{}]-【微信支付】-【异常】-【{}：{}】", tradeId, "exception", "系统繁忙");
		}
		log.info("[{}]-【微信支付】-【结束】", tradeId);
		return resMap;

	}

}
